import * as types from '../store/mutation'
import api from '../api/user'

const state = {
  user: {
    id: '',
    username: '',
    password: '',
    is_superuser: false
  },
  UsersList: [],
  UserAndHost:[]
};
const actions = {
  getIndexUser: function ({commit}) {
    api.getUserIndex(function (res) {
      commit(types.INDEX_USER, res)
    })
  },
  getIndexUserAndHost: function ({commit}) {
    api.getUserAndHost(function (res) {
      commit(types.INDEX_USER_HOST, res)
    })
  },
  createUserUpdate: function ({commit}, host) {
    commit(types.CREATE_USER, host)
  },
  deleteUserUpdate: function ({commit}, id) {
    commit(types.DELETE_USER, id)
  }
};
const mutations = {
  [types.INDEX_USER](state, res) {
    if (state.UsersList.length != 0) {
      state.UsersList = []
    }
    res.response.forEach(data => {
      state.UsersList.push(data)
    })
  },
  [types.INDEX_USER_HOST](state, res) {
    if (state.UserAndHost.length != 0) {
      state.UserAndHost = []
    }
    res.response.forEach(data => {
      state.UserAndHost.push(data)
    })
  },
  [types.CREATE_USER](state, res) {
    let check_is_updated_data = false;
    state.UsersList.forEach(user => {
      if (user.id == res.id) {
        check_is_updated_data = true;
      }
    });
    if (!check_is_updated_data) {
      state.UsersList.push(res.response)
    }
  },
  [types.DELETE_USER](state, id) {
    state.UsersList = state.UsersList.filter(host => {
      return host.id != id
    })
  }
};
const getters = {
  allUsersList: state => state.UsersList,
  allUsersHostList: state => state.UserAndHost
};
export default {
  state,
  actions,
  mutations,
  getters
}
